import http from '@/common/api/http.js'
import appConfig from '@/common/app-config.js';
import appStore from '@/common/app-store.js'

export default {
	isInitFinish: false,
	//token信息
	tokenInfo: {
		access_token: '', //token
		refresh_token: '', //刷新token
		expires_in: 0, //失效时间
	},
	// 初始化
	init() {
		if (this.isInitFinish) return;
		this.isInitFinish = true;
		this.initTokenInfo();
		console.log('app-user :: ');
		console.log('tokenInfo = ', JSON.stringify(this.tokenInfo));
	},
	//是否已登录,true=是,false=否
	isLogin() {
		if (this.tokenInfo && this.tokenInfo.access_token && this.tokenInfo.refresh_token) {
			return true
		}
		return false
	},
	/**
	 * 登录
	 * @param {Object} params
	 */
	async login(params) {
		return new Promise((resolve, reject) => {
			http.get('/auth/loginForBusiness', params)
				.then(res => {
					this.refreshToken(res);
					resolve(res);
				}).catch(err => {
					// this.$api.msg(err.msg);
					reject(err);
				})
		})
	},
	/**
	 * 退出登录
	 */
	async logout() {
		return new Promise((resolve, reject) => {
			try {
				this.cleanObj(this.tokenInfo);
				appStore.removeStorageSyncByKey(appStore.tokenInfo);
				resolve('');
			} catch (e) {
				reject(e);
			}

		})
	},
	cleanObj(oldData) {
		for (let key in oldData) {
			oldData[key] = '';
		}
	},
	updateObj(oldData, newData = '') {
		if (newData) {
			for (let key in newData) {
				let value = newData[key];
				oldData[key] = value;
			}
		}
	},
	/**
	 * 初始化or设置token
	 */
	initTokenInfo() {
		let storageToken = appStore.getStorageByKey(appStore.tokenInfo);
		if (storageToken) {
			this.tokenInfo = storageToken;
		}
	},
	/**
	 * 刷新token
	 * @param {Object} res
	 */
	refreshToken(res) {
		if (res) {
			this.updateObj(this.tokenInfo, res);
			appStore.setStorageByKey(appStore.tokenInfo, this.tokenInfo);
		}
	},
	/**
	 * 商家端APP刷新token
	 */
	async refreshTokenForBusiness() {
		return new Promise((resolve, reject) => {
			if (!this.isLogin()) {
				reject('');
			} else {
				http.post('/auth/refreshTokenForBusiness')
					.then(res => {
						this.refreshToken(res);
						resolve(res);
					}).catch(err => {
						// this.$api.msg(err.msg);
						reject(err);
					})
			}
		})
	}
}
